<template>
  <div class="doctor-patients">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <h2>患者管理</h2>
          <div class="header-actions">
            <el-button type="primary" @click="refreshData">
              <el-icon><Refresh /></el-icon> 刷新数据
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 搜索和筛选区域 -->
      <div class="filter-container">
        <el-form :inline="true" :model="searchForm" ref="searchFormRef">
          <el-form-item label="患者姓名">
            <el-input v-model="searchForm.patientName" placeholder="请输入患者姓名" clearable />
          </el-form-item>
          <el-form-item label="日期范围">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              :shortcuts="dateShortcuts"
              style="width: 320px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 患者列表 -->
      <el-table
        v-loading="loading"
        :data="patientList"
        style="width: 100%; min-width: 1200px;"
        border
        stripe
        row-key="id"
        :header-cell-style="{background:'#f5f7fa', color:'#606266', fontWeight: 'bold'}"
        :cell-style="{padding: '12px 0'}"
      >
        <el-table-column label="序号" type="index" width="80" align="center" />
        <el-table-column label="患者姓名" prop="patientName" min-width="120" align="center">
          <template #default="scope">
            {{ scope.row.patientName || scope.row.patient?.name || '--' }}
          </template>
        </el-table-column>
        <el-table-column label="性别" prop="gender" min-width="80" align="center">
          <template #default="scope">
            <el-tag size="small" :type="getGenderType(scope.row.patientGender)">
              {{ getGenderText(scope.row.patientGender) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="联系电话" prop="phone" min-width="140" align="center">
          <template #default="scope">
            {{ scope.row.patientPhone || '未提供' }}
          </template>
        </el-table-column>
        <el-table-column label="预约日期" prop="date" min-width="130" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.date) || '--' }}
          </template>
        </el-table-column>
        <el-table-column label="预约时间" prop="timeSlot" min-width="120" align="center">
          <template #default="scope">
            {{ scope.row.timeSlot || '08:00-11:30' }}
          </template>
        </el-table-column>
        <el-table-column label="就诊原因" prop="visitReason" min-width="150" align="center" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.visitReason || scope.row.reason || '--' }}
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status" min-width="120" align="center">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)" effect="light">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" min-width="280" align="center">
          <template #default="scope">
            <div class="action-buttons">
              <el-button 
                size="small" 
                type="primary" 
                @click="viewPatient(scope.row)"
                plain
              >
                <el-icon><View /></el-icon> 查看
              </el-button>
              <el-button 
                size="small" 
                type="success" 
                @click="startConsultation(scope.row)"
                v-if="scope.row.status === '预约中'"
                plain
              >
                <el-icon><Opportunity /></el-icon> 开始就诊
              </el-button>
              <el-button 
                size="small"
                type="info" 
                @click="viewRecord(scope.row)"
                v-if="scope.row.status === '已到诊'"
                plain
              >
                <el-icon><Document /></el-icon> 查看记录
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页控件 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 患者详情对话框 -->
      <el-dialog
        v-model="patientDetailDialogVisible"
        title="患者详情"
        width="60%"
        destroy-on-close
      >
        <div v-loading="patientDetailLoading">
          <el-descriptions title="基本信息" :column="2" border>
            <el-descriptions-item label="患者姓名">{{ currentPatient.name || currentPatient.patientName }}</el-descriptions-item>
            <el-descriptions-item label="性别">
              {{ getGenderText(currentPatient.gender || currentPatient.patientGender) }}
            </el-descriptions-item>
            <el-descriptions-item label="患者ID">{{ currentPatient.patientId }}</el-descriptions-item>
            <el-descriptions-item label="年龄">
              {{ currentPatient.age || calculateAge(currentPatient.birthDate) || currentPatient.patientAge || '未知' }}岁
            </el-descriptions-item>
            <el-descriptions-item label="联系电话">{{ currentPatient.phone || currentPatient.contactInfo?.phone }}</el-descriptions-item>
            <el-descriptions-item label="联系地址">{{ currentPatient.address || currentPatient.contactInfo?.address }}</el-descriptions-item>
          </el-descriptions>
          
          <el-divider />
          
          <el-descriptions title="医疗信息" :column="2" border v-if="currentPatient.medicalInfo">
            <el-descriptions-item label="血型">{{ currentPatient.medicalInfo.bloodType || '未知' }}</el-descriptions-item>
            <el-descriptions-item label="过敏史">{{ formatArrayField(currentPatient.medicalInfo.allergies) }}</el-descriptions-item>
            <el-descriptions-item label="慢性病">{{ formatArrayField(currentPatient.medicalInfo.chronicDiseases) }}</el-descriptions-item>
            <el-descriptions-item label="手术史">{{ formatArrayField(currentPatient.medicalInfo.surgeryHistory) }}</el-descriptions-item>
          </el-descriptions>
        </div>
        <template #footer>
          <el-button @click="patientDetailDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="startConsultationFromDetail">开始就诊</el-button>
        </template>
      </el-dialog>

      <!-- 医疗记录详情对话框 -->
      <el-dialog
        v-model="medicalRecordDetailDialogVisible"
        title="就诊记录详情"
        width="80%"
        destroy-on-close
      >
        <div v-loading="medicalRecordDetailLoading">
          <!-- 基本信息区域 -->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-card shadow="never" class="info-card">
                <template #header>
                  <div class="card-header">
                    <el-icon><Document /></el-icon>
                    <span>基本信息</span>
                  </div>
                </template>
                <el-descriptions :column="1" border>
                  <el-descriptions-item label="患者姓名">
                    {{ currentMedicalRecord.patientInfo?.name || currentMedicalRecord.patientName || '--' }}
                  </el-descriptions-item>
                  <el-descriptions-item label="就诊日期">
                    {{ formatDate(currentMedicalRecord.visitDate) || '--' }}
                  </el-descriptions-item>
                  <el-descriptions-item label="主治医生">
                    {{ currentMedicalRecord.doctorInfo?.name || currentMedicalRecord.doctorName || '--' }}
                  </el-descriptions-item>
                  <el-descriptions-item label="科室">
                    {{ currentMedicalRecord.departmentInfo?.name || currentMedicalRecord.departmentName || '--' }}
                  </el-descriptions-item>
                </el-descriptions>
              </el-card>
            </el-col>
            <el-col :span="12">
              <el-card shadow="never" class="info-card">
                <template #header>
                  <div class="card-header">
                    <el-icon><User /></el-icon>
                    <span>病史信息</span>
                  </div>
                </template>
                <el-descriptions :column="1" border>
                  <el-descriptions-item label="主诉">
                    {{ currentMedicalRecord.chiefComplaint || '--' }}
                  </el-descriptions-item>
                  <el-descriptions-item label="现病史">
                    {{ currentMedicalRecord.presentIllness || '--' }}
                  </el-descriptions-item>
                  <el-descriptions-item label="既往史">
                    {{ currentMedicalRecord.pastHistory || '--' }}
                  </el-descriptions-item>
                </el-descriptions>
              </el-card>
            </el-col>
          </el-row>

          <!-- 体格检查 -->
          <el-card shadow="never" class="info-card" style="margin-top: 20px;" v-if="currentMedicalRecord.physicalExamination">
            <template #header>
              <div class="card-header">
                <el-icon><Monitor /></el-icon>
                <span>体格检查</span>
              </div>
            </template>
            <el-descriptions :column="3" border>
              <el-descriptions-item label="体温(℃)">
                {{ currentMedicalRecord.physicalExamination?.temperature || '--' }}
              </el-descriptions-item>
              <el-descriptions-item label="脉搏(次/分)">
                {{ currentMedicalRecord.physicalExamination?.pulse || '--' }}
              </el-descriptions-item>
              <el-descriptions-item label="血压(mmHg)">
                {{ currentMedicalRecord.physicalExamination?.bloodPressure || '--' }}
              </el-descriptions-item>
              <el-descriptions-item label="身高(cm)">
                {{ currentMedicalRecord.physicalExamination?.height || '--' }}
              </el-descriptions-item>
              <el-descriptions-item label="体重(kg)">
                {{ currentMedicalRecord.physicalExamination?.weight || '--' }}
              </el-descriptions-item>
              <el-descriptions-item label="体质量指数">
                {{ calculateBMI(currentMedicalRecord.physicalExamination?.height, currentMedicalRecord.physicalExamination?.weight) }}
              </el-descriptions-item>
            </el-descriptions>
          </el-card>

          <!-- 诊断信息 -->
          <el-row :gutter="20" style="margin-top: 20px;">
            <el-col :span="12">
              <el-card shadow="never" class="info-card">
                <template #header>
                  <div class="card-header">
                    <el-icon><FirstAidKit /></el-icon>
                    <span>诊断结果</span>
                  </div>
                </template>
                <div v-if="currentMedicalRecord.diagnosis && currentMedicalRecord.diagnosis.length > 0">
                  <el-tag 
                    v-for="(diag, index) in formatDiagnosis(currentMedicalRecord.diagnosis)" 
                    :key="index" 
                    type="warning" 
                    style="margin-right: 8px; margin-bottom: 8px;"
                  >
                    {{ diag }}
                  </el-tag>
                </div>
                <div v-else class="no-data">暂无诊断信息</div>
              </el-card>
            </el-col>
            <el-col :span="12">
              <el-card shadow="never" class="info-card">
                <template #header>
                  <div class="card-header">
                    <el-icon><Edit /></el-icon>
                    <span>治疗方案</span>
                  </div>
                </template>
                <div v-if="currentMedicalRecord.treatmentPlan">
                  {{ currentMedicalRecord.treatmentPlan }}
                </div>
                <div v-else class="no-data">暂无治疗方案</div>
              </el-card>
            </el-col>
          </el-row>

          <!-- 关联数据按钮 -->
          <el-card shadow="never" class="info-card" style="margin-top: 20px;">
            <template #header>
              <div class="card-header">
                <el-icon><Link /></el-icon>
                <span>关联数据</span>
              </div>
            </template>
            <div class="action-buttons">
              <el-button type="primary" @click="viewRelatedPrescriptions">
                <el-icon><FirstAidKit /></el-icon>
                查看处方
              </el-button>
              <el-button type="success" @click="viewRelatedMedicalOrders">
                <el-icon><Document /></el-icon>
                查看医嘱
              </el-button>
            </div>
          </el-card>
        </div>
        <template #footer>
          <el-button @click="medicalRecordDetailDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="printMedicalRecord">
            <el-icon><Printer /></el-icon>
            打印记录
          </el-button>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { appointmentAPI, doctorAPI, patientAPI, medicalRecordAPI } from '@/utils/api'
import { formatDate } from '@/utils/date'
import { useUserStore } from '@/stores/user'
import { Refresh, View, Opportunity, Document, User, Monitor, FirstAidKit, Edit, Link, Printer } from '@element-plus/icons-vue'

// 路由实例
const router = useRouter()
const userStore = useUserStore()

// 数据加载状态
const loading = ref(false)

// 表格数据
const patientList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 搜索表单
const searchFormRef = ref(null)
const searchForm = reactive({
  patientName: '',
  startDate: '',
  endDate: ''
})

// 日期范围
const dateRange = ref([])

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    },
  },
]

// 监听日期范围变化
const updateDateRange = computed(() => {
  if (dateRange.value && dateRange.value.length === 2) {
    searchForm.startDate = dateRange.value[0]
    searchForm.endDate = dateRange.value[1]
  } else {
    searchForm.startDate = ''
    searchForm.endDate = ''
  }
})

// 获取医生ID
const getDoctorId = async () => {
  try {
    // 获取当前登录用户信息
    const userInfo = userStore.userInfo
    
    // 如果userInfo中有doctorId，直接使用
    if (userInfo && (userInfo.doctorId || userInfo.doctor)) {
      return userInfo.doctorId || userInfo.doctor
    }
    
    // 获取用户ID
    const userId = userStore.userId || userInfo?.id || userInfo?._id
    
    if (!userId) {
      ElMessage.error('用户未登录或无法获取用户ID')
      return null
    }

    // 通过用户ID获取医生信息
    const res = await doctorAPI.getDoctorByUserId(userId)
    
    if (res.success && res.data) {
      return res.data.id || res.data._id
    } else {
      // 尝试从window对象获取
      if (window.doctorId) {
        return window.doctorId
      }
      
      ElMessage.error('获取医生信息失败')
      return null
    }
  } catch (error) {
    console.error('获取医生ID失败:', error)
    ElMessage.error('获取医生信息失败，请重新登录')
    return null
  }
}

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    'pending': 'info',
    'confirmed': 'primary',
    'arrived': 'warning',
    'completed': 'success',
    'cancelled': 'danger',
    'no_show': 'warning',
    // 中文状态映射
    '预约中': 'info',
    '已确认': 'primary',
    '已到诊': 'warning', 
    '已完成': 'success',
    '已取消': 'danger',
    '未到诊': 'warning'
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    'pending': '待确认',
    'confirmed': '已确认',
    'arrived': '已到诊',
    'completed': '已完成',
    'cancelled': '已取消',
    'no_show': '未到诊',
    // 中文状态保持原样
    '预约中': '预约中',
    '已确认': '已确认',
    '已到诊': '已到诊',
    '已完成': '已完成',
    '已取消': '已取消',
    '未到诊': '未到诊'
  }
  return texts[status] || status || '未知'
}

// 获取性别类型
const getGenderType = (gender) => {
  if (!gender || gender === 'unknown') return 'info'
  
  const normalizedGender = String(gender).toLowerCase()
  
  if (normalizedGender === 'male' || normalizedGender === '男') {
    return 'primary'
  } else if (normalizedGender === 'female' || normalizedGender === '女') {
    return 'danger'
  } else {
    return 'info'
  }
}

// 获取性别文本
const getGenderText = (gender) => {
  if (!gender || gender === 'unknown') return '未知'
  
  const normalizedGender = String(gender).toLowerCase()
  
  if (normalizedGender === 'male' || normalizedGender === '男') {
    return '男'
  } else if (normalizedGender === 'female' || normalizedGender === '女') {
    return '女'
  } else {
    return '未知'
  }
}

// 数据处理函数 - 标准化患者数据格式
const processPatientData = (rawData) => {
  if (!Array.isArray(rawData)) return []
  
  return rawData.map(item => {
    // 统一处理患者姓名
    let patientName = item.patientName || item.patient?.name || item.name || '--'
    
    // 统一处理性别
    const getGender = (data) => {
      if (data.patientGender) return data.patientGender
      if (data.patient?.gender) return data.patient.gender
      if (data.gender) return data.gender
      return 'unknown'
    }
    
    // 统一处理联系电话
    const getPhone = (data) => {
      if (data.patientPhone) return data.patientPhone
      if (data.patient?.phone) return data.patient.phone
      if (data.patient?.contactInfo?.phone) return data.patient.contactInfo.phone
      if (data.phone) return data.phone
      if (data.contactInfo?.phone) return data.contactInfo.phone
      return ''
    }
    
    // 统一处理时间段
    const getTimeSlot = (data) => {
      if (data.timeSlot) return data.timeSlot
      if (data.period && data.scheduleInfo?.timeSlots) {
        const slots = data.scheduleInfo.timeSlots[data.period]
        if (slots) {
          return `${slots.startTime}-${slots.endTime}`
        }
      }
      // 默认时间段
      if (data.period === '上午') return '08:00-11:30'
      if (data.period === '下午') return '13:30-17:00'
      if (data.period === '晚上') return '18:00-21:00'
      return '08:00-11:30'
    }

    // 统一处理预约日期
    const getAppointmentDate = (data) => {
      if (data.appointmentDate) return data.appointmentDate
      if (data.date) return data.date
      if (data.visitDate) return data.visitDate
      if (data.scheduledDate) return data.scheduledDate
      return ''
    }

    // 统一ID处理 - 这是关键
    const getAppointmentId = (data) => {
      // 优先级：id > _id > appointmentId
      if (data.id) return data.id
      if (data._id) return data._id
      if (data.appointmentId) return data.appointmentId
      return null
    }

    // 处理患者ID
    const getPatientId = (data) => {
      if (data.patientId) return data.patientId
      if (data.patient?.id) return data.patient.id
      if (data.patient?._id) return data.patient._id
      return null
    }
    
    return {
      // 确保有唯一的预约ID
      id: getAppointmentId(item),
      appointmentId: getAppointmentId(item),
      patientName,
      patientGender: getGender(item),
      patientAge: item.patientAge || item.patient?.age || item.age || 0,
      patientId: getPatientId(item),
      patientPhone: getPhone(item),
      date: getAppointmentDate(item),
      timeSlot: getTimeSlot(item),
      period: item.period || '上午',
      visitReason: item.visitReason || item.reason || '常规就诊',
      status: item.status || 'confirmed',
      doctorId: item.doctorId,
      doctorName: item.doctorName,
      departmentId: item.departmentId,
      departmentName: item.departmentName,
      // 保留完整的原始数据用于调试
      _originalData: item
    }
  })
}

// 获取患者详细信息以补充缺失数据
const enrichPatientData = async (appointments) => {
  if (!Array.isArray(appointments) || appointments.length === 0) {
    return appointments
  }

  // 识别需要补充信息的患者ID
  const patientIdsToFetch = new Set()
  const enrichedAppointments = [...appointments]

  appointments.forEach((appointment, index) => {
    const patientId = appointment.patientId || 
                     (appointment.patient ? (appointment.patient.id || appointment.patient._id) : null)
    
    // 如果有患者ID但缺少关键信息（如性别），则需要查询
    if (patientId && (!appointment.patientGender || appointment.patientGender === 'unknown' || 
        !appointment.patientAge || !appointment.patientPhone || appointment.patientPhone.trim() === '')) {
      patientIdsToFetch.add(patientId)
    }
  })

  // 批量查询患者信息
  if (patientIdsToFetch.size > 0) {
    console.log('需要补充信息的患者ID:', Array.from(patientIdsToFetch))
    
    const patientDetailsMap = new Map()
    
    // 并发查询所有患者信息
    const fetchPromises = Array.from(patientIdsToFetch).map(async (patientId) => {
      try {
        const res = await patientAPI.getPatient(patientId)
        if (res.success && res.data) {
          patientDetailsMap.set(patientId, res.data)
          console.log(`成功获取患者 ${patientId} 的详细信息:`, res.data)
        }
      } catch (error) {
        console.warn(`获取患者 ${patientId} 详细信息失败:`, error)
      }
    })
    
    // 等待所有查询完成
    await Promise.all(fetchPromises)
    
    // 将查询到的患者信息合并到预约数据中
    enrichedAppointments.forEach((appointment, index) => {
      const patientId = appointment.patientId || 
                       (appointment.patient ? (appointment.patient.id || appointment.patient._id) : null)
      
      if (patientId && patientDetailsMap.has(patientId)) {
        const patientDetail = patientDetailsMap.get(patientId)
        
        // 合并患者详细信息，优先使用API返回的详细信息
        enrichedAppointments[index] = {
          ...appointment,
          // 患者基本信息 - 优先使用详细信息，但保持原有非空值
          patientName: appointment.patientName || patientDetail.name || patientDetail.username || '未知患者',
          // 性别处理：如果原始性别为空或unknown，使用详细信息
          patientGender: (appointment.patientGender && appointment.patientGender !== 'unknown') 
            ? appointment.patientGender 
            : (patientDetail.gender || appointment.patientGender || 'unknown'),
          // 年龄处理：如果原始年龄为空或0，使用详细信息
          patientAge: (appointment.patientAge && appointment.patientAge > 0) 
            ? appointment.patientAge 
            : (patientDetail.age || calculateAge(patientDetail.birthDate) || appointment.patientAge || 0),
          // 电话处理：如果原始电话为空，使用详细信息
          patientPhone: (appointment.patientPhone && appointment.patientPhone.trim()) 
            ? appointment.patientPhone 
            : (patientDetail.phone || patientDetail.contactInfo?.phone || appointment.patientPhone || ''),
          // 保存完整的患者信息用于详情查看
          patientDetail: patientDetail
        }
        
        console.log(`患者 ${patientId} 数据合并结果:`, {
          原始性别: appointment.patientGender,
          API性别: patientDetail.gender,
          最终性别: enrichedAppointments[index].patientGender,
          原始年龄: appointment.patientAge,
          API年龄: patientDetail.age,
          计算年龄: calculateAge(patientDetail.birthDate),
          最终年龄: enrichedAppointments[index].patientAge,
          原始电话: appointment.patientPhone,
          API电话: patientDetail.phone,
          API电话2: patientDetail.contactInfo?.phone,
          最终电话: enrichedAppointments[index].patientPhone
        })
      }
    })
    
    console.log(`成功补充了 ${patientDetailsMap.size} 个患者的详细信息`)
  }

  return enrichedAppointments
}

// 根据出生日期计算年龄
const calculateAge = (birthDate) => {
  if (!birthDate) return null
  
  try {
    const today = new Date()
    const birth = new Date(birthDate)
    let age = today.getFullYear() - birth.getFullYear()
    const monthDiff = today.getMonth() - birth.getMonth()
    
    if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
      age--
    }
    
    return age > 0 ? age : null
  } catch (error) {
    console.warn('计算年龄失败:', error)
    return null
  }
}

// 加载患者数据 - 修改数据处理逻辑
const loadPatients = async () => {
  loading.value = true
  try {
    const doctorId = await getDoctorId()
    if (!doctorId) {
      loading.value = false
      return
    }
    
    // 构建查询参数
    const params = {
      doctorId,
      page: currentPage.value,
      limit: pageSize.value,
      ...searchForm
    }
    
    // 移除空字段
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })
    
    console.log('查询医生预约列表参数:', params)
    
    // 调用API获取医生的预约列表
    const res = await appointmentAPI.getAppointments(params)
    
    if (res.success && res.data) {
      // 处理数据 - 使用标准化函数处理
      const rawData = res.data.appointments || res.data.items || res.data || []
      
      // 打印原始数据的ID信息用于调试
      if (Array.isArray(rawData) && rawData.length > 0) {
        console.log('获取到真实预约数据，ID格式示例:')
        rawData.forEach((item, index) => {
          console.log(`预约${index+1} ID:`, item.id || item._id || item.appointmentId)
          console.log(`预约${index+1} 患者ID:`, item.patientId || item.patient?.id || item.patient?._id)
          console.log(`预约${index+1} 性别:`, item.patientGender || item.patient?.gender || '未知')
        })
      } else {
        console.log('未获取到预约数据')
      }
      
      let processedData = processPatientData(rawData)
      
      // 补充患者详细信息
      console.log('开始补充患者详细信息...')
      processedData = await enrichPatientData(processedData)
      
      patientList.value = processedData
      total.value = res.data.total || patientList.value.length
      
      // 调试输出
      console.log('最终处理后数据:', patientList.value)
      console.log('患者性别信息:', patientList.value.map(p => ({ 
        name: p.patientName, 
        gender: p.patientGender,
        age: p.patientAge,
        phone: p.patientPhone
      })))
    } else {
      ElMessage.error('获取患者数据失败')
    }
  } catch (error) {
    console.error('加载患者数据失败:', error)
    ElMessage.error('加载患者数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索方法
const handleSearch = () => {
  currentPage.value = 1
  loadPatients()
}

// 重置搜索
const resetSearch = () => {
  searchFormRef.value.resetFields()
  dateRange.value = []
  handleSearch()
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  loadPatients()
}

// 当前页改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  loadPatients()
}

// 刷新数据
const refreshData = () => {
  loadPatients()
}

// 患者详情相关
const patientDetailDialogVisible = ref(false)
const patientDetailLoading = ref(false)
const currentPatient = ref({})

// 医疗记录相关
const medicalRecordDetailDialogVisible = ref(false)
const medicalRecordDetailLoading = ref(false)
const currentMedicalRecord = ref({})

// 格式化数组字段显示
const formatArrayField = (arr) => {
  if (!arr) return '无'
  if (Array.isArray(arr)) {
    return arr.length > 0 ? arr.join('、') : '无'
  }
  return String(arr) || '无'
}

// 查看患者详情
const viewPatient = async (row) => {
  patientDetailLoading.value = true
  patientDetailDialogVisible.value = true
  
  // 如果已经有完整的患者详细信息，直接使用
  if (row.patientDetail) {
    console.log('使用已缓存的患者详细信息:', row.patientDetail)
    currentPatient.value = {
      ...row,
      ...row.patientDetail,
      // 确保关键字段不被覆盖
      id: row.id || row.appointmentId,
      appointmentId: row.appointmentId || row.id,
      patientId: row.patientId
    }
    patientDetailLoading.value = false
    return
  }
  
  // 如果没有详细信息，设置基本信息并尝试获取
  currentPatient.value = { ...row }
  
  try {
    // 获取患者ID - 可能存在于不同的字段中
    const patientId = row.patientId || 
                     (row.patient ? (row.patient.id || row.patient._id) : null) || 
                     (row.patientInfo ? (row.patientInfo.id || row.patientInfo._id) : null)
    
    if (patientId) {
      console.log('尝试获取患者详细信息，患者ID:', patientId)
      // 调用患者API获取详细信息
      const res = await patientAPI.getPatient(patientId)
      
      if (res.success && res.data) {
        console.log('成功获取患者详细信息:', res.data)
        // 合并API返回的详细数据
        currentPatient.value = { 
          ...currentPatient.value, 
          ...res.data,
          // 确保关键字段不被覆盖
          id: row.id || row.appointmentId,
          appointmentId: row.appointmentId || row.id,
          patientId: patientId
        }
      } else {
        console.warn('获取患者详细信息失败:', res.message)
      }
    } else {
      // 如果没有找到患者ID，显示提示
      ElMessage.warning('未找到患者ID，仅显示基本信息')
      console.warn('未找到患者ID，行数据:', row)
    }
  } catch (error) {
    console.error('获取患者详情失败:', error)
    ElMessage.warning('获取患者详情失败，显示基本信息')
  } finally {
    patientDetailLoading.value = false
  }
}

// 从详情对话框开始就诊
const startConsultationFromDetail = () => {
  patientDetailDialogVisible.value = false
  startConsultation(currentPatient.value)
}

// 开始就诊
const startConsultation = async (row) => {
  console.log('开始就诊，患者数据:', row)
  
  // 验证预约状态 - 只有预约中状态才能开始就诊
  if (row.status !== '预约中') {
    ElMessage.warning('只有预约中的预约才能开始就诊')
    return
  }
  
  // 获取预约ID
  const appointmentId = row.appointmentId || row.id
  if (!appointmentId) {
    ElMessage.error('无法获取预约ID，请刷新页面重试')
    return
  }
  
  try {
    // 直接跳转到就诊页面，不修改预约状态
    console.log('准备跳转到就诊页面:', `/portal/doctor/consultation/${appointmentId}`)
    router.push(`/portal/doctor/consultation/${appointmentId}`)
  } catch (error) {
    console.error('跳转就诊页面失败:', error)
    ElMessage.error('跳转就诊页面失败：' + (error.message || '未知错误'))
  }
}

// 查看就诊记录
const viewRecord = async (row) => {
  // 获取预约ID
  const appointmentId = row.appointmentId || row.id
  if (!appointmentId) {
    ElMessage.error('无法获取预约ID')
    return
  }
  
  try {
    console.log('查询医疗记录，预约ID:', appointmentId)
    
    // 通过预约ID查询医疗记录
    const res = await medicalRecordAPI.getMedicalRecordByAppointment(appointmentId)
    
    if (res.success && res.data) {
      console.log('找到医疗记录:', res.data)
      // 设置当前医疗记录数据并显示详情对话框
      currentMedicalRecord.value = res.data
      medicalRecordDetailDialogVisible.value = true
    } else {
      ElMessage.info('该预约暂无就诊记录')
    }
  } catch (error) {
    console.error('查询就诊记录失败:', error)
    ElMessage.error('查询就诊记录失败：' + (error.message || '网络错误'))
  }
}

// 检查是否可以开始就诊
const canStartConsultation = (row) => {
  // 只有预约中状态可以开始就诊
  return row.status === '预约中'
}

// 检查是否可以查看记录
const canViewRecord = (row) => {
  // 只有已到诊状态可以查看记录
  return row.status === '已到诊'
}

// 计算BMI
const calculateBMI = (height, weight) => {
  if (!height || !weight || height <= 0 || weight <= 0) {
    return '--'
  }
  const heightInMeters = height / 100
  const bmi = weight / (heightInMeters * heightInMeters)
  return bmi.toFixed(1)
}

// 查看关联处方
const viewRelatedPrescriptions = () => {
  const medicalRecordId = currentMedicalRecord.value.id
  if (medicalRecordId) {
    // 跳转到处方查看页面
    router.push(`/portal/doctor/prescriptions?medicalRecordId=${medicalRecordId}`)
  } else {
    ElMessage.warning('无法获取医疗记录ID')
  }
}

// 查看关联医嘱
const viewRelatedMedicalOrders = () => {
  const medicalRecordId = currentMedicalRecord.value.id
  if (medicalRecordId) {
    // 跳转到医嘱查看页面
    router.push(`/portal/doctor/medical-orders?medicalRecordId=${medicalRecordId}`)
  } else {
    ElMessage.warning('无法获取医疗记录ID')
  }
}

// 打印医疗记录
const printMedicalRecord = () => {
  ElMessage.info('打印功能开发中...')
}

// 格式化诊断结果
const formatDiagnosis = (diagnosis) => {
  if (!diagnosis || !Array.isArray(diagnosis)) return []
  return diagnosis.map(diag => {
    if (typeof diag === 'string') return diag
    if (typeof diag === 'object' && diag.name) return diag.name
    return String(diag)
  })
}

// 页面加载时获取数据
onMounted(() => {
  loadPatients()
})
</script>

<style scoped>
.doctor-patients {
  width: 100%;
  min-width: 1200px;
  overflow-x: auto;
  padding: 0 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.filter-container {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
  min-width: 1000px;
}

.filter-container .el-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.filter-container .el-form-item {
  margin-bottom: 10px;
  margin-right: 15px;
}

.pagination-container {
  text-align: right;
  padding-top: 20px;
}

/* 表格样式优化 */
:deep(.el-table) {
  font-size: 14px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  min-width: 1200px;
}

:deep(.el-table__header) {
  font-weight: bold;
}

:deep(.el-table .cell) {
  padding: 10px 8px;
  white-space: nowrap;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 6px;
  flex-wrap: nowrap;
  min-width: 260px;
}

.action-buttons .el-button {
  flex-shrink: 0;
  min-width: 80px;
}

:deep(.el-button.is-plain) {
  transition: all 0.3s;
}

:deep(.el-button.is-plain:not(.is-disabled):hover) {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

/* 表格容器样式 */
:deep(.el-card__body) {
  padding: 20px;
  overflow-x: auto;
}

/* 移动端响应式 */
@media (max-width: 1300px) {
  .doctor-patients {
    min-width: auto;
    padding: 0 10px;
  }
  
  :deep(.el-table) {
    min-width: 1200px;
  }
  
  .filter-container {
    min-width: auto;
  }
}

@media (max-width: 768px) {
  .doctor-patients {
    padding: 0 5px;
  }
  
  .filter-container .el-form {
    display: flex;
    flex-direction: column;
  }
  
  .filter-container .el-form-item {
    margin-right: 0;
    margin-bottom: 10px;
  }
  
  .action-buttons {
    flex-direction: column;
    align-items: center;
    gap: 4px;
  }
  
  .action-buttons .el-button {
    width: 100%;
    margin-left: 0;
    margin-bottom: 3px;
    min-width: auto;
  }
}

.patient-history {
  margin-top: 20px;
}

.patient-history h3 {
  margin-bottom: 15px;
  font-size: 16px;
  color: #409eff;
  border-left: 4px solid #409eff;
  padding-left: 10px;
}

.info-card {
  margin-bottom: 20px;
}

.info-card .card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: bold;
  color: #409eff;
}

.no-data {
  text-align: center;
  color: #909399;
  padding: 20px;
  font-style: italic;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 15px;
  padding: 10px 0;
}

.action-buttons .el-button {
  min-width: 120px;
}

/* 医疗记录详情对话框样式 */
:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.info-card .el-card__header) {
  padding: 12px 20px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #ebeef5;
}

:deep(.info-card .el-card__body) {
  padding: 15px 20px;
}

:deep(.el-descriptions__header) {
  background-color: #f5f7fa;
}

:deep(.el-descriptions__label) {
  font-weight: bold;
  width: 120px;
}

:deep(.el-tag) {
  margin: 2px;
}
</style> 